package front

import (
	"encoding/json"
	"fmt"
	"geekai/api/handler"
	"geekai/core"
	"geekai/core/types"
	"geekai/model"
	"geekai/service"
	"geekai/utils"
	"github.com/gin-gonic/gin"
	"github.com/imroc/req/v3"
	"gorm.io/gorm"
	"io"
	"regexp"
	"time"
)

type RealtimeHandler struct {
	handler.BaseHandler
	userService *service.UserService
}

func NewRealtimeHandler(app *core.AppServer, db *gorm.DB, userService *service.UserService) *RealtimeHandler {
	return &RealtimeHandler{
		BaseHandler: handler.BaseHandler{App: app, DB: db},
		userService: userService,
	}
}

// VoiceChat godoc
// @Summary      OpenAI 实时语音对话，一次性对话
// @Description  OpenAI 实时语音对话，一次性对话
// @Tags         前台-实时语音对话
// @Accept       json
// @Produce      json
// @Success      200  {object}  types.BizVo{}
// @Router       /api/realtime/voice [post]
// @Security ApiKeyAuth
func (h *RealtimeHandler) VoiceChat(c *gin.Context) {
	var apiKey model.ApiKey
	err := h.DB.Session(&gorm.Session{}).Where("type", "realtime").Where("enabled", true).First(&apiKey).Error
	if err != nil {
		utils.ERROR(c, "查询实时通话 API-KEY 出现错误："+err.Error())
		return
	}

	var response utils.OpenAIResponse
	client := req.C()
	if len(apiKey.ProxyURL) > 5 {
		client.SetProxyURL(apiKey.ApiURL)
	}
	apiURL := fmt.Sprintf("%s/v1/chat/completions", apiKey.ApiURL)
	log.Infof("发送 %s 请求，API KEY：%+v，PROXY：%s，Model：%s", apiURL,
		apiKey, apiKey.ApiURL, "advanced-voice")
	r, err := client.R().SetHeader("Body-Type", "application/json").
		SetHeader("Authorization", "Bearer "+apiKey.Value).
		SetBody(types.ApiRequest{
			Model:       "advanced-voice",
			Temperature: 0.9,
			MaxTokens:   1024,
			Stream:      false,
			Messages: []interface{}{
				types.Message{
					Role:    "user",
					Content: "实时语音通话",
				},
			},
		}).Post(apiURL)
	if err != nil {
		utils.ERROR(c, fmt.Sprintf("请求 OpenAI API失败：%v", err))
		return
	}
	if r.IsErrorState() {
		utils.ERROR(c, fmt.Sprintf("请求 OpenAI API失败：%v", r.Status))
		return
	}

	body, _ := io.ReadAll(r.Body)
	err = json.Unmarshal(body, &response)
	if err != nil {
		utils.ERROR(c, fmt.Sprintf("解析API数据失败：%v, %s", err, string(body)))
	}

	// 更新 API KEY 的最后使用时间
	h.DB.Model(&apiKey).UpdateColumn("last_used_at", time.Now().Unix())

	// 扣减算力
	userId := h.GetLoginUserId(c)
	err = h.userService.DecreasePower(int(userId), h.App.SysConfig.AdvanceVoicePower, model.PowerLog{
		Type:   types.PowerConsume,
		Model:  "advanced-voice",
		Remark: "实时语音通话",
	})

	if err != nil {
		utils.ERROR(c, "扣减算力出现错误："+err.Error())
		return
	}

	log.Infof("Response：%v", response.Choices[0].Message.Content)
	// 提取链接
	re := regexp.MustCompile(`\[(.*?)\]\((.*?)\)`)
	links := re.FindAllStringSubmatch(response.Choices[0].Message.Content, -1)
	var url = ""
	if len(links) > 0 {
		url = links[0][2]
	}
	utils.SUCCESS(c, url)
}
